const router = require('koa-router')()
const url = require('url')


router.use(async (ctx, next) => {
  //模板引擎配置全局的变量(state是模板引擎里边的属性)
  ctx.state.__HOST__ = `http://${ctx.request.headers.host}`
  let pathname = url.parse(ctx.request.url).pathname.substring(1)
  //左侧菜单的分割
  let splitUrl = pathname.split('/')
  //配置全局信息
  ctx.state.G = {
    url: splitUrl,
    userinfo: ctx.session.userinfo
  }
  //通过session判断是否登录
  if (ctx.session.userinfo) {
    await next()
  } else {
    if (pathname === 'admin/login' || pathname === 'admin/login/doLogin' || pathname === 'admin/login/code') {
      await next()
    } else {
      ctx.redirect('/admin/login')
    }
  }
})

router.get('/', async (ctx) => {
  await ctx.render('admin/index')
})
let index = require('./admin/index')
let login = require('./admin/login')
let user = require('./admin/user')
let manage = require('./admin/manage')

router.use(index)
router.use('/login', login)
router.use('/user', user)
router.use('/manage', manage)

module.exports = router.routes()